/**
 * @desc 商品列表
 * @author yd_zhaorongjun
 */
<template>
  <div class="gl_heightFull">
    <div class="demo-input-suffix gl_searchBox">
      <el-row :gutter="20">
        <el-col :md="5" :lg="3">
          <p>按商品分组选择</p>
          <el-select v-model="Api_GET_MallProductQO.ProductGroupId" size="mini" placeholder="请选择" filterable @change="refreshList()">
            <el-option label="全部" value="" />
            <el-option v-for="item in productGroup" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-col>
        <el-col :md="5" :lg="3">
          <p>商品名称</p>
          <el-input v-model="Api_GET_MallProductQO.Filter" placeholder="请输入" size="mini" clearable @change="refreshList()" />
        </el-col>
        <el-col :md="14" :lg="18" :xl="18" style="text-align:right">
          <!-- 查询按钮 -->
          <el-button style="margin-top:27px" type="primary" size="mini" @click="refreshList()">{{ $t('button.query') }}</el-button>
          <!-- 重置按钮 -->
          <el-button style="margin-top:27px" type="warning" size="mini" @click="refreshSearchForm">{{ $t('button.Reset') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <template>
      <el-row style="margin:15px 0 8px 0">
        <el-col :span="24">
          <el-button type="primary" size="mini" @click="editOfAdd()">添加商品</el-button>
          <el-button type="warning" size="mini" @click="clickGrouping()">批量分组</el-button>
          <el-button type="danger" size="mini" @click="clickBatchDelete()">批量删除</el-button>
          <el-button type="success" size="mini" @click="clickBatchState()">批量上架</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="tableLoading" :data="tableData" class="gl_table_noBorder" size="mini" style="width: 100%;" @sort-change="changeSort" @selection-change="selection">
        <el-table-column type="selection" label-class-name="selection" width="55" />
        <el-table-column type="index" label="序号" align="center" width="55" />
        <el-table-column label="商品信息" align="center" width="70">
          <template slot-scope="{row}">
            <img class="roodsPhoto" :src="getStaticFileUrl(row.images[0].imageUrl)" alt="" @error="errorPhoto" @mouseenter="showGoodsImg(...arguments, row.images[0].imageUrl)" @mouseleave="hideGoodsImg(row.images[0].imageUrl)">
          </template>
        </el-table-column>
        <el-table-column
          label=""
          min-width="280"
        >
          <template slot-scope="{row}">
            {{ row.name || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="价格" sortable="custom" width="80">
          <template slot-scope="{row}">
            <span>
              {{ row.price || row.price === 0 ? '￥' + row.price/100 : '--' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="库存" sortable="custom" width="80">
          <template slot-scope="{row}">
            <span>
              {{ row.count || '--' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="所属分组" min-width="110">
          <template slot-scope="{row}">
            <span>
              {{ row.group.name || '--' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          width="80"
        >
          <template slot-scope="{row}">
            <span v-if="row.productStatusCode === 'OnShelf'" class="gl_color_success">
              <!-- <i class="iconfont icon_state" style="vertical-align: middle;" /> -->
              <span>销售中</span>
            </span>
            <span v-if="row.productStatusCode === 'InStorage'" class="gl_color_info">
              <!-- <i class="iconfont icon_state" style="vertical-align: middle;" /> -->
              <span>仓库中</span>
            </span>
            <span v-if="row.productStatusCode === 'Deleted'" class="gl_color_error">
              <!-- <i class="iconfont icon_state" style="vertical-align: middle;" /> -->
              <span>已删除</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建人"
          min-width="100"
        >
          <template slot-scope="{row}">
            {{ row.creatorName || '--' }}
          </template>
        </el-table-column>
        <!-- 创建时间 -->
        <el-table-column
          label="创建时间"
          width="140"
        >
          <template slot-scope="{row}">
            <span v-if="row.creationTime">
              {{ row.creationTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}
            </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" width="200">
          <template slot-scope="{row}">
            <el-button v-if="row.productStatusCode !== 'Deleted'" size="mini" type="text" @click="editOfAdd(row, 'edit')">编辑</el-button>
            <el-button v-if="row.productStatusCode === 'OnShelf'" size="mini" type="text" @click="clickChangeStatus(row, 'InStorage')">下架</el-button>
            <el-button v-if="row.productStatusCode === 'InStorage'" size="mini" type="text" @click="clickChangeStatus(row, 'OnShelf')">上架</el-button>
            <el-button v-if="row.productStatusCode !== 'Deleted'" size="mini" type="text" style="color:#FF3434" @click="clickDelete(row)">删除</el-button>
            <template v-if="row.productStatusCode !== 'Deleted' && row.productStatusCode === 'OnShelf'">
              <el-button v-if="row.isRecommended" size="mini" type="text" style="color:#FFBA00" @click="clickCancelRecommend(row)">取消</el-button>
              <el-button v-else size="mini" type="text" style="color:#FFBA00" @click="clickRecommend(row)">推荐</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <img v-if="isShowImg && getStaticFileUrl(bigImg)" class="roodsBigPhoto" :style="position" :src="getStaticFileUrl(bigImg)" alt="" @error="errorPhoto">
      <el-row class="gl_pt_20" style="text-align: right;">
        <el-pagination
          :current-page="Api_GET_MallProductQO.Page"
          :page-size="Api_GET_MallProductQO.MaxResultCount"
          :total="totalPage"
          layout="total,sizes,prev,pager,next,jumper"
          :page-sizes="[10, 20, 30, 40]"
          @size-change="sizeChange"
          @current-change="pageIndexChange"
        />
      </el-row>
    </template>
    <dialogBatchGroup ref="dialogBatchGroup" :product-group="productGroup" @insert="changeBatchGroup" />
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { translateByCode } from '@/lib/getTransData';
import defaultImg from '@/assets/images/face_default.png';
import dialogBatchGroup from './dialogBatchGroup';
// import { CopyData } from '@/lib';
import {
  Api_GET_MallProductGroupQO,
  Api_GET_MallProductQO
} from '@/lib/form/shoppingmall/swaggerForm';
import {
  api_GET_MallProductGroup,
  api_GET_MallStoreCurrent,
  api_GET_MallProduct,
  api_POST_MallProductGroup,
  api_PUT_MallProductGroupId,
  api_PUT_MallProductGroupIdSortOrder,
  api_PUT_MallProductIdStatus,
  api_POST_MallProductRecommend,
  api_DELETE_MallProductRecommend,
  api_PUT_MallProductGroupListGroupId,
  api_PUT_MallProductStatusList
} from '@/extend/api/shoppingmallswaggerApi/app.js';
export default {
  components: {
    dialogBatchGroup
  },
  data() {
    return {
      defaultImg: defaultImg,
      Api_GET_MallProductGroupQO: new Api_GET_MallProductGroupQO(),
      Api_GET_MallProductQO: new Api_GET_MallProductQO(),
      tableLoading: false,
      totalPage: 0,
      tableData: [],
      productGroup: [],
      selectData: [], // 选中的数据
      rowId: '', //
      tableRow: {}, //
      position: {
        left: 0,
        top: 0
      },
      currentPage: 1,
      isShowImg: false,
      bigImg: '',
      storeId: ''
    };
  },
  computed: {
    ...mapState({
      dictAll: state => state.dict.dictAll
    })
  },
  watch: {
    'storeId': {
      handler: function(val) {
        if (!val) return;
        this.getMallProductGroup();
        this.refreshList();
      }
    }
  },
  created() {
    this.getDict();
    this.api_GET_MallStoreCurrent();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取当前用户店铺信息
    api_GET_MallStoreCurrent() {
      api_GET_MallStoreCurrent({ IncludeStatus: true }).then(res => {
        this.storeId = res.id || '';
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 获取分组列表
    getMallProductGroup() {
      this.Api_GET_MallProductGroupQO.Page = 1;
      // this.Api_GET_MallProductGroupQO.SkipCount = (this.Api_GET_MallProductGroupQO.Page - 1) * this.Api_GET_MallProductGroupQO.MaxResultCount;
      this.Api_GET_MallProductGroupQO.StoreId = this.storeId;
      this.Api_GET_MallProductGroupQO.MaxResultCount = 999;
      api_GET_MallProductGroup(this.Api_GET_MallProductGroupQO).then(res => {
        this.productGroup = res.items;
        this.Api_GET_MallProductQO.ProductGroupId = '';
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 刷新列表
    refreshList(page) {
      this.tableLoading = true;
      this.Api_GET_MallProductQO.Page = page || 1;
      this.Api_GET_MallProductQO.SkipCount = (this.Api_GET_MallProductQO.Page - 1) * this.Api_GET_MallProductQO.MaxResultCount;
      this.Api_GET_MallProductQO.StoreId = this.storeId;
      this.Api_GET_MallProductQO.IncludeImages = true;
      this.Api_GET_MallProductQO.IncludeGroup = true;
      this.Api_GET_MallProductQO.ProductGroupId = this.Api_GET_MallProductQO.ProductGroupId || '';
      this.Api_GET_MallProductQO.ProductStatusCodes = ['InStorage'];
      this.Api_GET_MallProductQO.IsRecommended = null;
      this.Api_GET_MallProductQO.MinPrice = null;
      this.Api_GET_MallProductQO.MaxPrice = null;
      this.Api_GET_MallProductQO.MinCount = null;
      this.Api_GET_MallProductQO.MaxCount = null;
      this.Api_GET_MallProductQO.Sorting = this.Api_GET_MallProductQO.Sorting || 'creationTime DESC';

      api_GET_MallProduct(this.Api_GET_MallProductQO).then(res => {
        this.tableData = res.items;
        this.totalPage = res.totalCount;
        this.tableLoading = false;
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 重置搜索表单
    refreshSearchForm() {
      this.Api_GET_MallProductQO = new Api_GET_MallProductQO();
      this.Api_GET_MallProductQO.IsRecommended = '';
      this.refreshList();
    },
    // 添加或修改
    editOfAdd(row, type) {
      if (this.productGroup.length < 1) {
        this.$message({ type: 'warning', message: '请先添加商品分组！' });
        return;
      }
      const _name = type === 'edit' ? 'EditGoods' : 'AddGoods';
      const _id = type === 'edit' ? row.id : '';
      this.$router.push({
        name: _name,
        params: { id: _id }
      });
    },
    // 添加组别
    groupInsert(data) {
      const _this = this;
      api_POST_MallProductGroup(data).then(res => {
        this.$message({
          // 添加成功！
          message: translateByCode('alert.addSuccessfully'),
          type: 'success'
        });
        _this.refreshList(this.Api_GET_MallProductQO.Page);
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 修改组别
    groupUpdate(data) {
      const _this = this;
      api_PUT_MallProductGroupId(this.rowId, data).then(res => {
        this.$message({
          // 添加成功！
          message: '修改成功！',
          type: 'success'
        });
        _this.refreshList(this.Api_GET_MallProductQO.Page);
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 删除按钮
    clickDelete(row) {
      const _this = this;
      // 您确定要删除 xxx 吗？ zh
      const _confirmStr = ` ${translateByCode('alert.wantDelete')} [ ${row.name} ] ${translateByCode('alert.ma')}`;
      this.$confirm(_confirmStr, translateByCode('alert.warning'), {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_PUT_MallProductIdStatus(row.id, { statusCode: 'Deleted' }).then(res => {
          this.$message({
            type: 'success',
            // 删除成功！
            message: translateByCode('alert.deleteSuccessfully')
          });
          _this.refreshList(this.Api_GET_MallProductQO.Page);
        }, error => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      });
    },
    // 下架商品按钮
    clickChangeStatus(row, type) {
      const _this = this;
      // 您确定要下架 xxx 吗？
      const _text = type === 'OnShelf' ? '上架' : '下架';
      const _confirmStr = ` 您确定要${_text} [ ${row.name} ] ${translateByCode('alert.ma')}`;
      this.$confirm(_confirmStr, translateByCode('alert.warning'), {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_PUT_MallProductIdStatus(row.id, { statusCode: type }).then(res => {
          this.$message({
            type: 'success',
            message: '操作成功！'
          });
          _this.refreshList(this.Api_GET_MallProductQO.Page);
        }, error => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      });
    },
    // 推荐商品按钮
    clickRecommend(row) {
      const _this = this;
      api_POST_MallProductRecommend({ productId: row.id }).then(res => {
        this.$message({
          type: 'success',
          message: '推荐成功！'
        });
        _this.refreshList(this.Api_GET_MallProductQO.Page);
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 取消推荐商品按钮
    clickCancelRecommend(row) {
      const _this = this;
      api_DELETE_MallProductRecommend({ productId: row.id }).then(res => {
        this.$message({
          type: 'success',
          message: '取消推荐成功！'
        });
        _this.refreshList(this.Api_GET_MallProductQO.Page);
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 更新商品排序
    setSortOrder(row, index, type) {
      const _this = this;
      this.tableLoading = true;
      api_PUT_MallProductGroupIdSortOrder(row.id, { offset: type === 'up' ? -1 : 1 }).then(res => {
        this.$message({
          // 添加成功！
          message: translateByCode('alert.addSuccessfully'),
          type: 'success'
        });
        _this.refreshList(this.Api_GET_MallProductQO.Page);
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
        this.tableLoading = false;
      });
    },
    sizeChange(MaxResultCount) {
      this.Api_GET_MallProductQO.MaxResultCount = MaxResultCount;
      this.refreshList();
    },
    pageIndexChange(currentPage) {
      this.refreshList(currentPage);
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultImg;
    },
    showGoodsImg(event, img) {
      const _this = this;
      _this.bigImg = img;
      const _img = event.target; // 这里就是获取到的dom元素
      const _position = _img.getBoundingClientRect();
      this.timeOut = setTimeout(() => {
        _this.isShowImg = true;
        _this.$set(_this.position, 'left', _position.left + 60 + 'px');
        _this.$set(_this.position, 'top', _position.top + 'px');
      }, 300);
    },
    hideGoodsImg() {
      const _this = this;
      clearTimeout(this.timeOut);
      _this.isShowImg = false;
    },
    // 选中的数据
    selection(val) {
      this.selectData = [];
      if (val.length > 0) {
        val.forEach(item => {
          this.selectData.push(item.id);
        });
      }
    },
    // 批量分组弹框
    clickGrouping() {
      if (this.selectData.length > 0) {
        this.$refs.dialogBatchGroup.open();
      } else {
        this.$message({
          message: '请选择商品',
          type: 'warning'
        });
      }
    },
    // 批量分组
    changeBatchGroup(data) {
      const _this = this;
      api_PUT_MallProductGroupListGroupId(data, this.selectData).then(res => {
        this.$message({
          // 添加成功！
          message: translateByCode('alert.addSuccessfully'),
          type: 'success'
        });
        _this.$refs.dialogBatchGroup.dialogVisible = false;
        _this.$refs.dialogBatchGroup.submitLoading = false;
        _this.refreshList(this.Api_GET_MallProductQO.Page);
      }, error => {
        _this.$refs.dialogBatchGroup.submitLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 批量删除
    clickBatchDelete() {
      if (this.selectData.length > 0) {
        const _confirmStr = '您确定要批量删除吗？';
        this.$confirm(_confirmStr, translateByCode('alert.warning'), {
          confirmButtonText: translateByCode('alert.confirm'),
          cancelButtonText: translateByCode('alert.cancel'),
          type: 'warning'
        }).then(() => {
          api_PUT_MallProductStatusList({ statusCode: 'Deleted' }, this.selectData).then(res => {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.refreshList(this.Api_GET_MallProductQO.Page);
          }, error => {
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        });
      } else {
        this.$message({
          message: '请选择商品',
          type: 'warning'
        });
      }
    },
    // 批量上架
    clickBatchState() {
      if (this.selectData.length > 0) {
        const _confirmStr = '您确定要批量上架吗？';
        this.$confirm(_confirmStr, translateByCode('alert.warning'), {
          confirmButtonText: translateByCode('alert.confirm'),
          cancelButtonText: translateByCode('alert.cancel'),
          type: 'warning'
        }).then(() => {
          api_PUT_MallProductStatusList({ statusCode: 'OnShelf' }, this.selectData).then(res => {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.refreshList(this.Api_GET_MallProductQO.Page);
          }, error => {
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        });
      } else {
        this.$message({
          message: '请选择商品',
          type: 'warning'
        });
      }
    },
    changeSort (val) {
      console.log(val);
      // 升序："Price"，倒序："Price DESC"
      if (val.column.label === '价格' && val.order === 'ascending') {
        this.Api_GET_MallProductQO.Sorting = 'Price';
      } else if (val.column.label === '价格' && val.order === 'descending') {
        this.Api_GET_MallProductQO.Sorting = 'Price DESC';
      } else if (val.column.label === '库存' && val.order === 'ascending') {
        this.Api_GET_MallProductQO.Sorting = 'count';
      } else if (val.column.label === '库存' && val.order === 'descending') {
        this.Api_GET_MallProductQO.Sorting = 'count DESC';
      } else {
        this.Api_GET_MallProductQO.Sorting = '';
      }
      this.refreshList(this.Api_GET_MallProductQO.Page);
    }
  }
};
</script>
<style lang="scss" scoped>
.preview_close,
.preview_top,
.preview_bottom {
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  vertical-align: middle;
  color: rgba(0,0,0,0.65);;
}

.preview_close:hover,
.preview_top:hover,
.preview_bottom:hover {
  color: #5CBDFF;
}
.disable_move {
  color: #C0C4CC;
  cursor: not-allowed;
}
  .roodsPhoto{
    width: 60px;
    height: 60px;
    vertical-align: middle;
  }
  .roodsBigPhoto{
    width: 310px;
    height: 280px;
    position: fixed;
    z-index: 10;
  }
  .icon_color {
    color: #1682e6;
  }
</style>
